"""Build ping test"""
import daos_build

IOIL_TEST_SRC = ['test_ioil.c']
IOIL_BUILD_STATIC = False

def build_static_tests(env):
    """build the static interception library"""

    #This code requires a full static chain or some major
    #linker magic.  Disabled for now.
    if IOIL_BUILD_STATIC:
        to_build = env.get('libioil')
        if to_build in ('none', 'shared'):
            return []

        ilenv = env.Clone()

        ioil_opt = '-Wl,--whole-archive -lioil -Wl,--no-whole-archive'
        ioil_script = "%s/../il/ioil-ld-opts" % Dir('.').abspath
        ilenv.AppendUnique(CFLAGS=['-Wl,@%s' % ioil_script, ioil_opt])
        ilenv.AppendUnique(LINKFLAGS=['-static', '-Wl,--whole-archive',
                                      '-lioil', '-Wl,--no-whole-archive'])

        il_test = []
        for test in IOIL_TEST_SRC:
            il_test += ilenv.Program(test)

        return il_test

    return []

def scons():
    """Scons function"""

    Import('dfuse_env', 'prereqs')

    if not prereqs.check_component('cunit'):
        print("\n************************************************")
        print("CUnit packages must be installed to enable tests")
        print("************************************************\n")
        # Just returning is the desired behavior here.  The utest target
        # has yet to be defined so the build will just fail.
        return

    # Set options which are used throughout the src.
    tenv = dfuse_env.Clone()
    tenv.AppendUnique(CFLAGS=['-pthread'])
    tenv.AppendUnique(CPPDEFINES=['_GNU_SOURCE'])
    tenv.AppendUnique(CPPPATH=['..'])
    tenv.AppendUnique(CPPPATH='../il')
    tenv.AppendUnique(LIBPATH='../il')
    tenv.AppendUnique(RPATH_FULL='$PREFIX/lib64')
    tenv.AppendUnique(LINKFLAGS=["-Wl,-rpath-link=%s" % Dir('../../dfs').path])

    prereqs.require(tenv, 'cunit')

    il_test = []

    lfenv = tenv.Clone()
    lfenv.AppendUnique(CPPPATH='../il')
    lfenv.AppendUnique(OBJPREFIX='lf_')
    lfenv.AppendUnique(CPPDEFINES='LARGEFILE64_SOURCE')

    tenv.AppendUnique(CPPDEFINES=['_FILE_OFFSET_BITS=64'])

    il_test += build_static_tests(tenv)
    il_test += build_static_tests(lfenv)

    tenv.AppendUnique(OBJPREFIX='s_')
    tenv.AppendUnique(LIBS=['ioil', 'daos'])
    lfenv.AppendUnique(OBJPREFIX='s_')
    lfenv.AppendUnique(LIBS=['ioil', 'daos'])

    for test in IOIL_TEST_SRC:
        il_test += daos_build.test(tenv, test, install_off="../../../..")
        il_test += daos_build.test(lfenv, test, install_off="../../../..")

    Default(il_test)

    tenv.Install('$PREFIX/lib/daos/TESTING/tests', il_test)

if __name__ == "SCons.Script":
    scons()
